package com.curd.demo.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.curd.demo.entity.News;
import com.curd.demo.service.INewsService;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

@RestController
@RequestMapping("/News")
public class NewsController {

    @Resource
    private INewsService NewsService;

    @PostMapping
    public boolean save(@RequestBody News news) {
        news.setTime(new Date());//获取时间
        return NewsService.saveOrUpdate(news);
    }

    @DeleteMapping("/{id}")
    public Boolean delete(@PathVariable Integer id) {
        return NewsService.removeById(id);
    }

    @PostMapping("/del/batch")
    public boolean deleteBatch(@RequestBody List<Integer> ids) {
        return NewsService.removeByIds(ids);
    }

    @GetMapping
    public List<News> findAll() {
        return NewsService.list();
    }

    @GetMapping("/{id}")
    public News findOne(@PathVariable Integer id) {
        return NewsService.getById(id);
    }

    @GetMapping("/page")
    public Page<News> findPage(@RequestParam Integer pageNum,
                               @RequestParam Integer pageSize,
                               @RequestParam(defaultValue = "") String title) {

        QueryWrapper<News> queryWrapper = new QueryWrapper<>();
        queryWrapper.orderByDesc("title");
        if (!"".equals(title)) {
            queryWrapper.like("title", title);
        }
        return NewsService.page(new Page<>(pageNum, pageSize), queryWrapper);
    }
}
